package controllers;

import gestioneDatabase.User.StylesheetModifier;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.User;
import openIDService.VerifyUser;
import utilities.GestoreLink;
import controllersUtilities.StylesController;

/**
 * Controller per la pagina delle impostazioni
 * 
 */
@SuppressWarnings("serial")
@WebServlet("/settings")
public class SettingsController extends HttpServlet {

	private StylesController stylesController = new StylesController();
	private StylesheetModifier stylesheetModifier;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		VerifyUser user = new VerifyUser(request);

		if (user.isAuthorized()) {
			ArrayList<File> styles = stylesController.getAllStyles();
			request.setAttribute("styles", styles);
			request.getRequestDispatcher(
					GestoreLink.getGestore().getElement("Settings")).forward(
					request, response);
		} else {
			response.sendRedirect(GestoreLink.getGestore().getElement("login"));
		}
	}
	
	/**
	 * Modifica lo stilesheet, prende lo user e gli imposta lo stilesheet stesso.
	 * 
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String stylesheet = req.getParameter("styles");
		User user = (User) req.getSession().getAttribute("identity");

		if (stylesheet.equals("Seleziona stile")) {
			resp.sendRedirect("settings");
			return;
		}
		if (user != null) {
			user.setStylesheet(stylesheet);
			stylesheetModifier = new StylesheetModifier(user.getOpenId(),
					stylesheet);
			stylesheetModifier.execute();
			resp.sendRedirect("settings?savedmessage=Salvato!");
		} else
			resp.sendRedirect("login");

	}
}
